<template>
  <div class="content">
    <div class="header">
      <h3 class="title">轮播图列表</h3>
      <el-button type="primary" @click="handleNewcarouselClick"
        >添加轮播图</el-button
      >
    </div>
    <div class="table">
      <el-table :data="carouselList" border style="width: 100%">
        <el-table-column
          align="center"
          type="index"
          label="序号"
          width="60px"
        />

        <el-table-column
          align="center"
          label="轮播图标题"
          prop="name"
          width="300px"
        />
        <el-table-column
          align="center"
          label="状态"
          prop="status"
          width="150px"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              inline-prompt
              active-value="active"
              inactive-value="inactive"
              active-text="是"
              inactive-text="否"
              size="large"
              @change="statusChange(scope.row)"
            />
          </template>
        </el-table-column>

        <el-table-column align="center" label="轮播图" prop="image_url">
          <template #default="scope">
            <img style="width: 50px" :src="scope.row.image_url" alt="" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间" prop="created_at">
          <template #default="scope">
            {{ formatUTC(scope.row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="200px">
          <template #default="scope">
            <el-button
              size="small"
              icon="Delete"
              type="danger"
              text
              @click="handleDeleteBtnClick(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="carouselTotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog v-model="dialogVisible" title="新建轮播图" width="50%" center>
      <div class="form">
        <el-form
          :model="formData"
          :rules="formRules"
          label-width="100px"
          size="large"
          ref="formRef"
        >
          <el-form-item label="轮播图标题" prop="carouselName">
            <el-input
              v-model="formData.carouselName"
              placeholder="请输入轮播图标题"
            />
          </el-form-item>
          <el-form-item label="轮播图" prop="image_url">
            <template #default>
              <el-upload
                class="avatar-uploader"
                :action="`${BASE_URL}/file/avatar`"
                :headers="{
                  Authorization: loginStore.token // 假设 token 是从 Vuex 中获取的
                }"
                accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                name="avatar"
              >
                <img
                  v-if="formData.image_url"
                  :src="formData.image_url"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </template>
          </el-form-item>
          <el-form-item label="轮播图标题" prop="carouselName">
            <el-switch
              v-model="formData.status"
              inline-prompt
              active-value="active"
              inactive-value="inactive"
              active-text="是"
              inactive-text="否"
              size="large"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { ref, reactive } from 'vue'
import { formatUTC } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormRules, ElForm, UploadProps } from 'element-plus'
import useLoginStore from '@/store/login/login'
import useSettingStore from '@/store/main/setting/setting'
import { BASE_URL } from '@/service/config'
const emit = defineEmits(['newClick', 'editClick'])
const settingtore = useSettingStore()
const { carouselList, carouselTotalCount } = storeToRefs(settingtore)
console.log(carouselList, 12)
const currentPage = ref(1)
const pageSize = ref(10)
const searchData = ref<any>()

fetchCarouselListData()

// 3.页码相关的逻辑
function handleSizeChange() {
  fetchCarouselListData()
}
function handleCurrentChange() {
  fetchCarouselListData()
}
// 4.定义函数, 用于发送网络请求
function fetchCarouselListData(formData?: any) {
  // 1.获取offset/size
  const limit = pageSize.value
  const offset = (currentPage.value - 1) * limit
  // 2.发起网络请求
  if (formData) {
    searchData.value = formData
    settingtore.getCarouselsAction({ ...formData, limit, offset })
    return
  }
  settingtore.getCarouselsAction({ limit, offset })
}

// 5.删除数据
async function handleDeleteBtnClick(id: number) {
  ElMessageBox.confirm(`确认删除这个轮播图吗`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await settingtore.removeCarouselAction(id, searchData.value)
    ElMessage({
      type: 'success',
      message: '删除轮播图成功',
      duration: 1000
    })
  })
}
// 状态切换
async function statusChange(row: any) {
  await settingtore.updateCarouselStatusAction(row.id, row.status)
}

// 添加轮播图
const dialogVisible = ref(false)
const formData = reactive<any>({
  carouselName: '',
  image_url: '',
  status: 'active'
})
const formRules: FormRules = {
  carouselName: [
    { required: true, message: '请输入轮播图标题', trigger: 'blur' }
  ],
  image_url: [{ required: true, message: '请上传轮播图', trigger: 'blur' }],
  status: [{ required: true, message: '请选择轮播图状态', trigger: 'blur' }]
}

// 上传图片
const loginStore = useLoginStore()
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  formData.image_url = response.data.tempUrl
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
function handleNewcarouselClick() {
  dialogVisible.value = true
}
const formRef = ref<InstanceType<typeof ElForm>>()
function handleConfirmClick() {
  dialogVisible.value = false
  formRef.value?.validate(async (valid) => {
    if (valid) {
      // 创建新的用户
      await settingtore.addCarouselAction(formData)
      ElMessage({
        type: 'success',
        message: '新建轮播图成功'
      })
      fetchCarouselListData()
    }
  })
}

defineExpose({
  fetchCarouselListData
})
</script>

<style lang="less" scoped>
.content {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 10px;

  .title {
    font-size: 22px;
  }
}

.table {
  :deep(.el-table__cell) {
    padding: 12px 0;
  }

  .el-button {
    margin-left: 0;
    padding: 5px 8px;
  }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  background-color: #f0f2f5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
